//
//  AppDelegate.swift
//  Weibo10
//
//  Created by male on 15/10/14.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
 
        setupAppearance()
        
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.whiteColor()
        
        window?.rootViewController = defaultRootViewController
        
        window?.makeKeyAndVisible()
        
        
        
        // 监听通知
        NSNotificationCenter.defaultCenter().addObserverForName(WBSwitchRootVieControllerNotification, object: nil, queue: nil) {
            [weak self] (notification) -> Void in
            // 接受同名的任何通知，都跳转到主控制器中
            let vc = notification.object != nil ?WelcomeViewController() :MainViewController()
            
            self?.window?.rootViewController = vc
        }
        
        return true
    }
    
    deinit {
        
        // 注销通知
        NSNotificationCenter.defaultCenter().removeObserver(self, name: WBSwitchRootVieControllerNotification,
            object: nil
        )
    }
    
    /// 设置全局外观 - 在很多应用程序中，都会在 AppDelegate 中设置所有需要控件的全局外观
    private func setupAppearance() {
        // 修改导航栏的全局外观 － 要在控件创建之前设置，一经设置全局有效
        UINavigationBar.appearance().tintColor = WBAppearanceTintColor
        UITabBar.appearance().tintColor = WBAppearanceTintColor
    }
}

// MARK: - 界面切换代码
extension AppDelegate {
    
    //  启动的跟视图的控制器
    private var defaultRootViewController: UIViewController {
        // 判断是否登录
        if UserAccountViewModel.sharedUserAccount.userLogon {
            return isNewVersion ? NewFeatureViewController() : WelcomeViewController()
        }
        
        // 如果没有登录返回主控制器
        return MainViewController()
    }
    

    // 判断是否是新版本
    private var isNewVersion: Bool {
        
        // 获取当前版本号
        let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        
        // 数字版本号
        let version = Double(currentVersion)
        
        
        //  读取之前的版本号
        let sandboxVersionKey = "sandboxVersionKey"
        let sandboxVersion = NSUserDefaults.standardUserDefaults().doubleForKey(sandboxVersionKey)
        
        // 每次执行都保存最新的版本号
       if version != sandboxVersion {
            
            // 保存本号
            NSUserDefaults.standardUserDefaults().setDouble(version!, forKey: sandboxVersionKey)
        }
        return version > sandboxVersion
        
    }
    
}

